#include "stdio.h"
#include <iostream>
#include "net/event_loop_thread.h"
#include "net/event_loop_thread_pool.h"

static rr::nio::EventLoopThread::Sptr loop_thread;
static rr::nio::EventLoopThreadPool::Sptr loop_thread_pool;

void TestEventLoopThreadStart()
{
    printf("TestEventLoopThreadStart\n");
    {
        if(loop_thread.get()) {
            return;
        }

        loop_thread = std::make_shared<rr::nio::EventLoopThread>();

        auto func_init = [](rr::nio::EventLoop::Sptr loop) {
            printf("EventLoopThread func_init\n");
        };

        auto func_exit = [](rr::nio::EventLoop::Sptr loop) {
            printf("EventLoopThread func_exit\n");
        };

        loop_thread->SetInitCallback(func_init);
        loop_thread->SetExitCallback(func_exit);

        loop_thread->StartLoop();
    }

    printf("TestEventLoopThreadPoolStart\n");
    {
        if(loop_thread_pool) {
            return;
        }
        loop_thread_pool = std::make_shared<rr::nio::EventLoopThreadPool>("test_pool");
        loop_thread_pool->Start(4);
    }

    return;
}

void TestEventLoopThreadStop()
{
    do
    {
        printf("TestEventLoopThreadStop begin\n");
        if(!loop_thread.get()) {
            break;;
        }

        loop_thread->StopLoop();
        printf("TestEventLoopThreadStop end\n");
        loop_thread.reset();
    } while (0);
    

    do
    {
        printf("TestEventLoopThreadPoolStop begin\n");
        if(!loop_thread_pool.get()) {
            break;;
        }

        loop_thread_pool->Stop();
        printf("TestEventLoopThreadPoolStop end\n");
        loop_thread_pool.reset();
    } while (0);

    return;
}


void TestEventLoopThreadFunc()
{
    do
    {
        printf("TestEventLoopThreadFunc\n");
        if(!loop_thread.get()) {
            printf("the loop_thread is null\n");
            break;
        }

        rr::nio::EventLoop::Sptr loop  = loop_thread->GetLoop();
        if(!loop.get()) {
            printf("the loop is null\n");
            break;
        }

        loop->RunInLoop([]() {
            printf("RunInLoop TestEventLoopThreadFunc 111\n");
        });
    } while (0);
    

    do
    {
        printf("TestEventLoopThreadPoolFunc\n");
        if(!loop_thread_pool.get()) {
            printf("the loop_thread_pool is null\n");
            break;
        }

        for(uint32_t i = 0; i < 5; i++) {
            rr::nio::EventLoop::Sptr loop  = loop_thread_pool->GetLoopByIndex(i);
            if(!loop.get()) {
                printf("the loop is null i=%u\n", i);
                continue;
            }

            loop->RunInLoop([i]() {
                std::thread::id thread_id = std::this_thread::get_id();
                std::cout << "RunInLoop TestEventLoopThreadPoolFunc i="  <<  i << " thread_id: " << thread_id << std::endl;
            });
        }
    } while (0);

    return;
}
